<template>
  <div class="goods-update">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-page-header @back="goBack">
            <template #content>编辑商品</template>
          </el-page-header>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="goods-form"
        v-loading="loading">
        <el-form-item label="商品id" prop="id">
          <el-input v-model="form.id" disabled/>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="goods-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="customUpload">
            <img v-if="form.imgs" :src="'http://127.0.0.1:8080/file/'+ form.imgs" class="goods-image" />
            <el-icon v-else class="goods-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            只能上传 jpg/png 文件，且不超过 2MB
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            提交
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { getGoodsByIdAPI, updateGoodsAPI } from '../../../api/goods'
import { uploadFileAPI } from '../../../api/file'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
const submitLoading = ref(false)

const form = reactive({
  name: '',
  price: 0,
  imgs: '',
  previewUrl:''
})

const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  imgs: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ],
}

// 获取商品详情
const getGoodsDetail = async () => {
  loading.value = true
  try {
    const res = await getGoodsByIdAPI(route.params.id)
    if (res.code !== '200') {
      ElMessage.error('获取商品详情失败')
      return
    }
    console.log(res);
    
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取商品详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 上传图片前的验证
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
   // 创建本地预览URL
   form.previewUrl = URL.createObjectURL(file)
  return true
}

// 自定义上传方法
const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    const res = await uploadFileAPI(formData)
    console.log(res);
    if(res.code !== '200') {
      ElMessage.error(res.msg || '上传失败')
      return
    }
    
    form.imgs = res.data
    ElMessage.success('上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
    form.previewUrl = ''
  }
}

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const res = updateGoodsAPI(form)
        console.log(res);
        ElMessage.success('修改成功')
        goBack()
      } catch (error) {
        console.error('修改商品失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  getGoodsDetail()
})
</script>

<style scoped>
.goods-update {
  .card-header {
    padding: 10px 0;
  }

  .goods-form {
    max-width: 800px;
    margin: 0 auto;
    padding-top: 20px;
  }

  .goods-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;

    &:hover {
      border-color: #409EFF;
    }
  }

  .goods-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .goods-image {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style> 